//优惠券
//相比优惠码，优惠券是一次性的，而且不可共享
(function() {
	var config = require("../_include/config");
	var db = require("../db/index");
	var md5 = require("../_include/md5");
	var helper = require("../_include/helper");
	var db_table_name = config.dbname.ticket;
	var db_id_prefix = config.dbIdPrefix.ticket;
	//构造函数
	var _con = function(info) {
		if (!info) {
			throwCusError("参数错误，优惠券信息不可为空");
		}
		var self = this;
		self._id = db_id_prefix + "B:" + info.bus_id + "|T:" + info.ticket_factory_id + "|U:" + info.user_id;

		self.bus_id = info.bus_id;
		self.ticket_factory_id = info.ticket_factory_id;
		self.ticket_factory = TicketFactoryCon.get(this.ticket_factory_id);
		self.user_id = info.user_id;

		self.uid = _con.buildTicketUid(self);

		//使用情况
		self.info = {};
		self.setInfo({});

		self.state = _con.STATE.未使用;

		self.create_time = +new Date;

		db.insert(db_table_name, self);
		console.log("生成了一个优惠券：", self._id);
	};

	module.exports = _con;

	//技能
	_con.prototype = require("./skill");

	_con.STATE = {
		未使用: 1,
		已使用: 2,
		已过期: 3
	};

	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		return _con.getInstance(result);
	};
	_con.getInstance = function(result) {
		if (result) {
			result.__proto__ = _con.prototype;
			if (result.state === _con.STATE.未使用 && result.ticket_factory.info.diedline <= +new Date) {
				result.state = _con.STATE.已过期
				result.save();
			}
		}
		return result;
	};
	//生成默认的描述信息
	_con.buildTicketUid = function(instance) {
		var uid = _string_to_num(instance.bus_id, 4) + _string_to_num(instance.ticket_factory_id, 4) + _string_to_num(instance.user_id, 4);
		//4位校验位
		var check_code = _string_to_num(uid, 4);
		return uid + check_code;
	}

	function _string_to_num(str, bit) {
		var res = 0;
		for (var i = 0; i < str.length; i += 1) {
			res += str.charCodeAt(i);
		}
		if (bit) {
			res = String(res).substr(-bit)
		}
		return res;
	};
	_con.ticketId_has_user = function(ticket_id, user_id) {
		return ticket_id.indexOf("|U:" + user_id) !== -1;
	};

	var TicketFactoryCon = require("../ticket_factory/_con");
}());